package com.neuedu.web.common;

import com.neuedu.web.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author 金山
 * 项目：javaweb
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/11/1816:20
 */
public class BaseMethodController   extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         *  *     /web/user/list
         *  *     /web/user/save
         *  *     /web/user/insert
         *  *     /web/user/delete
         */
        String requestURI = req.getRequestURI();
        String target = requestURI.substring(requestURI.lastIndexOf("/")+1);


        Class aClass = this.getClass();
        try {
            //根据 target  获取到  本类的方法
            Method declaredMethod = aClass.getDeclaredMethod(target, HttpServletRequest.class, HttpServletResponse.class);
            // /web/user/list     declaredMethod   --> public void list  this.list();
            // /web/user/save     declaredMethod   --> public void save   this.save();
            declaredMethod.setAccessible(true); //可以让 private的方法 也能执行




            //执行方法
            Object result = declaredMethod.invoke(this,req,resp);

            //只要报错，将 Controller 方法返回的具体对象放到 data中返回
            /***
             *   code:200
             *   msg:''
             *   data:
             */

            //如果 Controller返回 void  不需要  使用json工具 写出
            if(  !"void".equals( declaredMethod.getReturnType().getName())){
                JSONUtils.write(resp, Res.ok(result));
            }


        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            // Map result = new HashMap();
            // result.put("code1",404);
            // result.put("msg","请求路径不存在");

            JSONUtils.write(resp, Res.urlNotFound());

        } catch (Exception e) {
            e.printStackTrace();
            // Map result = new HashMap();
            // result.put("code",500);
            // result.put("msg","内部错误");
            JSONUtils.write(resp,Res.error(e.getMessage()));
        }
    }


}

